package com.trace.demo.controller;

import com.trace.demo.entity.Order;
import com.trace.demo.entity.User;
import com.trace.demo.repository.OrderRepository;
import com.trace.demo.repository.UserRepository;
import com.trace.demo.repository.ProductRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.View;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ProductRepository productRepository;
    private View error;

    /**
     * 订单DTO类，用于将OrderStatus枚举映射为前端需要的中文状态
     */
    private static class OrderDTO {
        private final Order order;
        private final String statusDisplay; // 中文状态显示，修改为final以确保始终被设置
        private String customerName; // 新增：客户名称
        private String customerPhone; // 新增：客户电话

        public OrderDTO(Order order) {
            this.order = order;
            // 设置状态中文显示
            if (order.getStatus() != null) {
                switch (order.getStatus()) {
                    case PENDING:
                        this.statusDisplay = "待支付";
                        break;
                    case PAID:
                        this.statusDisplay = "已支付";
                        break;
                    case SHIPPED:
                        this.statusDisplay = "已发货";
                        break;
                    case DELIVERED:
                        this.statusDisplay = "已送达";
                        break;
                    case COMPLETED:
                        this.statusDisplay = "已完成";
                        break;
                    case CANCELLED:
                        this.statusDisplay = "已取消";
                        break;
                    default:
                        this.statusDisplay = order.getStatus().toString();
                        break;
                }
            } else {
                this.statusDisplay = "未知状态";
            }

            // 初始化客户信息 - 直接使用Order实体的字段
            if (order.getCustomer() != null) {
                this.customerName = order.getCustomer().getUsername();
                this.customerPhone = order.getCustomer().getPhone();
            } else {
                // 直接使用Order实体上的字段，如果有的话
                this.customerName = order.getCustomerName();
                this.customerPhone = order.getCustomerPhone();

                // 如果还是空，设置默认值
                if (this.customerName == null || this.customerName.isEmpty()) {
                    this.customerName = "客户" + (order.getId() % 1000);
                }
                if (this.customerPhone == null) {
                    this.customerPhone = "";
                }
            }
        }

        // 将Order的所有字段转换为Map，加上statusDisplay字段
        public Map<String, Object> toMap() {
            Map<String, Object> map = new HashMap<>();
            map.put("id", order.getId());
            map.put("orderNumber", order.getOrderNumber());
            map.put("orderNo", order.getOrderNo());
            map.put("quantity", order.getQuantity());
            map.put("unit", order.getUnit() != null ? order.getUnit() : "件");
            map.put("unitPrice", order.getUnitPrice());
            map.put("price", order.getPrice());
            map.put("totalAmount", order.getTotalAmount());
            map.put("orderStatus", this.statusDisplay); // 使用中文状态
            map.put("status", order.getStatus()); // 同时保留原始枚举值，以防需要
            map.put("productName", order.getProductName());
            map.put("batchNumber", order.getBatchNumber());
            map.put("orderDate", order.getOrderDate());
            map.put("paymentDate", order.getPaymentDate());
            map.put("paymentMethod", order.getPaymentMethod());
            map.put("shippingAddress", order.getShippingAddress());
            map.put("deliveryAddress", order.getShippingAddress()); // 为兼容前端，添加deliveryAddress
            map.put("shippingDate", order.getShippingDate());
            map.put("deliveryDate", order.getDeliveryDate());
            map.put("logisticsCompany", order.getLogisticsCompany());
            map.put("trackingNumber", order.getTrackingNumber());
            map.put("notes", order.getNotes());
            map.put("remark", order.getNotes()); // 为兼容前端，添加remark
            map.put("dealerId", order.getDealerId());
            map.put("sales",order.getSales());
            map.put("location",order.getLocation());
            // 如果关联了产品，添加产品信息
            if (order.getProduct() != null) {
                map.put("productId", order.getProduct().getId());
                if (order.getProductName() == null || order.getProductName().isEmpty()) {
                    map.put("productName", order.getProduct().getProductName());
                }
                map.put("productCode", order.getProduct().getProductCode());
                if (order.getBatchNumber() == null || order.getBatchNumber().isEmpty()) {
                    map.put("batchNumber", order.getProduct().getBatchNumber());
                }
            }

            // 添加客户信息 - 使用类的字段而不是复杂的解析
            map.put("customerName", this.customerName);
            map.put("customerPhone", this.customerPhone);
            if (order.getCustomer() != null) {
                map.put("customerId", order.getCustomer().getId());
            }

            return map;
        }
    }

    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAllOrders(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String orderNumber,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String orderStatus,
            @RequestParam(required = false) String[] dateRange) {

        try {
            // 创建分页请求
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("id").descending());

            // 获取订单分页数据
            Page<Order> orderPage = orderRepository.findAll(pageable);

            // 转换Order为OrderDTO并提取为Map集合，以便加入状态的中文显示
            List<Map<String, Object>> orderDTOs = orderPage.getContent().stream()
                .map(order -> new OrderDTO(order).toMap())
                .collect(Collectors.toList());

            // 创建分页响应
            Map<String, Object> response = new HashMap<>();
            response.put("content", orderDTOs);          // 使用转换后的DTOs
            response.put("totalElements", orderPage.getTotalElements());
            response.put("totalPages", orderPage.getTotalPages());
            response.put("size", orderPage.getSize());
            response.put("number", orderPage.getNumber());

            return ResponseEntity.ok(new ApiResponse<>(true, "Orders retrieved successfully", response));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(new ApiResponse<>(false, "Error retrieving orders: " + e.getMessage(), null));
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getOrderById(@PathVariable Long id) {
        Optional<Order> orderOpt = orderRepository.findById(id);
        if (!orderOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Order not found with id: " + id, null));
        }

        // 转换为DTO并返回Map格式
        Map<String, Object> orderMap = new OrderDTO(orderOpt.get()).toMap();
        return ResponseEntity.ok(new ApiResponse<>(true, "Order retrieved successfully", orderMap));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Order>> createOrder(@RequestBody Map<String, Object> orderData, Errors errors) {
        try {
            System.out.println("接收到的订单数据: " + orderData);
            Order order = new Order();

            order.setLocation(orderData.get("location").toString());

            order.setSales(orderData.get("sales").toString());


            // 生成订单号 - 同时设置orderNumber和orderNo
            String orderNoValue;
            if (orderData.get("orderNumber") == null || orderData.get("orderNumber").toString().isEmpty()) {
                orderNoValue = "ORD-" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
                order.setOrderNumber(orderNoValue);
                order.setOrderNo(orderNoValue); // 直接设置orderNo字段
            } else {
                orderNoValue = orderData.get("orderNumber").toString();
                order.setOrderNumber(orderNoValue);
                order.setOrderNo(orderNoValue); // 直接设置orderNo字段
            }

            // 设置基本字段
            Double quantity = 1.0; // 默认数量为1
            if (orderData.get("quantity") != null) {
                try {
                    if (orderData.get("quantity") instanceof Integer) {
                        quantity = Double.valueOf((Integer) orderData.get("quantity"));
                    } else if (orderData.get("quantity") instanceof Double) {
                        quantity = (Double) orderData.get("quantity");
                    } else {
                        quantity = Double.parseDouble(orderData.get("quantity").toString());
                    }
                } catch (Exception e) {
                    System.out.println("解析数量出错，使用默认值1: " + e.getMessage());
                }
            }
            order.setQuantity(quantity > 0 ? quantity : 1.0);

            Double unitPrice = 0.0; // 默认单价为0
            if (orderData.get("unitPrice") != null) {
                try {
                    if (orderData.get("unitPrice") instanceof Integer) {
                        unitPrice = Double.valueOf((Integer) orderData.get("unitPrice"));
                    } else if (orderData.get("unitPrice") instanceof Double) {
                        unitPrice = (Double) orderData.get("unitPrice");
                    } else {
                        unitPrice = Double.parseDouble(orderData.get("unitPrice").toString());
                    }
                } catch (Exception e) {
                    System.out.println("解析单价出错，使用默认值0: " + e.getMessage());
                }
            }
            order.setUnitPrice(unitPrice >= 0 ? unitPrice : 0.0);

            // 计算并设置总金额
            Double totalAmount = quantity * unitPrice;
            order.setTotalAmount(totalAmount);

            // 设置单位
            if (orderData.get("unit") != null && !orderData.get("unit").toString().isEmpty()) {
                order.setUnit(orderData.get("unit").toString());
            } else {
                order.setUnit("件"); // 默认单位
            }

            // 设置产品关联
            Long productId = null;
            if (orderData.get("productId") != null) {
                try {
                    if (orderData.get("productId") instanceof Integer) {
                        productId = Long.valueOf((Integer) orderData.get("productId"));
                    } else if (orderData.get("productId") instanceof Long) {
                        productId = (Long) orderData.get("productId");
                    } else {
                        productId = Long.parseLong(orderData.get("productId").toString());
                    }
                } catch (Exception e) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "产品ID格式不正确: " + e.getMessage(), null));
                }

                if (productId == null || productId <= 0) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "产品ID必须大于0", null));
                }

                // 从产品仓库获取产品对象并关联
                Optional<com.trace.demo.entity.Product> product = productRepository.findById(productId);
                if (!product.isPresent()) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "未找到ID为 " + productId + " 的产品", null));
                }
                order.setProduct(product.get());

                // 设置产品名称
                if (product.get().getProductName() != null && !product.get().getProductName().isEmpty()) {
                    order.setProductName(product.get().getProductName());
                } else {
                    // 如果产品名称为空，设置默认值
                    order.setProductName("未命名产品");
                }

                // 设置批次号
                if (product.get().getBatchNumber() != null && !product.get().getBatchNumber().isEmpty()) {
                    order.setBatchNumber(product.get().getBatchNumber());
                } else {
                    // 如果批次号为空，设置默认值
                    order.setBatchNumber("默认批次");
                }
            } else {
                // product_id 不能为空
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ApiResponse<>(false, "产品ID是必填项", null));
            }

            // 设置price字段 (与unitPrice保持一致)
            order.setPrice(order.getUnitPrice());

            // 设置客户信息
            if (orderData.get("customerName") != null) {
                order.setShippingAddress(orderData.get("deliveryAddress") != null ?
                    orderData.get("deliveryAddress").toString() : "");

                // 直接设置customerName字段
                order.setCustomerName(orderData.get("customerName").toString());

                // 设置customerPhone字段
                if (orderData.get("customerPhone") != null) {
                    order.setCustomerPhone(orderData.get("customerPhone").toString());
                }
            }

            // 设置备注
            if (orderData.get("remark") != null && !orderData.get("remark").toString().trim().isEmpty()) {
                order.setNotes(orderData.get("remark").toString());
            }

            // 设置经销商ID
            Long dealerId = 1L; // 默认经销商ID
            if (orderData.get("dealerId") != null) {
                try {
                    if (orderData.get("dealerId") instanceof Integer) {
                        dealerId = Long.valueOf((Integer) orderData.get("dealerId"));
                    } else if (orderData.get("dealerId") instanceof Long) {
                        dealerId = (Long) orderData.get("dealerId");
                    } else {
                        dealerId = Long.parseLong(orderData.get("dealerId").toString());
                    }
                } catch (Exception e) {
                    System.out.println("解析经销商ID出错，使用默认值1: " + e.getMessage());
                }
            }
            order.setDealerId(dealerId > 0 ? dealerId : 1L);

            // 设置订单日期
            order.setOrderDate(LocalDateTime.now());

            // 设置状态
            order.setStatus(Order.OrderStatus.PENDING);

            // 最终验证：确保所有必填字段都有值
            if (order.getProductName() == null || order.getProductName().isEmpty()) {
                order.setProductName("未命名产品");
            }
            if (order.getBatchNumber() == null || order.getBatchNumber().isEmpty()) {
                order.setBatchNumber("默认批次");
            }
            if (order.getPrice() == null) {
                order.setPrice(order.getUnitPrice() != null ? order.getUnitPrice() : 0.0);
            }
            if (order.getUnitPrice() == null) {
                order.setUnitPrice(order.getPrice() != null ? order.getPrice() : 0.0);
            }
            if (order.getQuantity() == null) {
                order.setQuantity(1.0);
            }
            if (order.getTotalAmount() == null) {
                order.setTotalAmount(order.getQuantity() * order.getUnitPrice());
            }
            if (order.getDealerId() == null) {
                order.setDealerId(1L);
            }

            System.out.println("准备保存的订单数据: " + order);
        Order savedOrder = orderRepository.save(order);
            System.out.println("订单保存成功，ID: " + savedOrder.getId());




            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(new ApiResponse<>(true, "订单创建成功", savedOrder));
        } catch (Exception e) {
            String errored="创建订单发生错误:";
            e.printStackTrace();
            Order orders = orderRepository.findByProductId(Long.valueOf(orderData.get("productId").toString()));
            if (orders !=null) {
                // 处理空值情况
                errored="当前产品已经创建过订单:";
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body(new ApiResponse<>(false,errored + e.getMessage(), null));
                                .body(new ApiResponse<>(false,errored,null));

        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Order>> updateOrder(
            @PathVariable Long id,
            @RequestBody Map<String, Object> orderData) {
        try {
            System.out.println("接收到的订单更新数据: " + orderData);
            System.out.println("URL路径中的订单ID: " + id);

            // 使用URL路径中的ID
            Long orderId = id;

            // 如果请求体中也有ID，确保它们匹配
            if (orderData.get("id") != null) {
                Long bodyId;
                try {
                    if (orderData.get("id") instanceof Integer) {
                        bodyId = Long.valueOf((Integer) orderData.get("id"));
                    } else if (orderData.get("id") instanceof Long) {
                        bodyId = (Long) orderData.get("id");
                    } else {
                        bodyId = Long.parseLong(orderData.get("id").toString());
                    }

                    if (!bodyId.equals(orderId)) {
                        System.out.println("警告: URL路径ID (" + orderId + ") 与请求体ID (" + bodyId + ") 不匹配，将使用URL路径ID");
                    }
                } catch (Exception e) {
                    System.out.println("解析请求体ID出错: " + e.getMessage() + "，将使用URL路径ID");
                }
            }

            // 查找现有订单
            Optional<Order> existingOrderOpt = orderRepository.findById(orderId);
            if (!existingOrderOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "未找到ID为 " + orderId + " 的订单", null));
            }

            Order existingOrder = existingOrderOpt.get();
            System.out.println("找到现有订单: " + existingOrder);

            // 更新订单号
            if (orderData.get("orderNumber") != null) {
                String orderNoValue = orderData.get("orderNumber").toString();
                existingOrder.setOrderNumber(orderNoValue);
                existingOrder.setOrderNo(orderNoValue); // 同时更新orderNo字段
            }

            // 更新数量
            if (orderData.get("quantity") != null) {
                try {
                    Double quantity;
                    if (orderData.get("quantity") instanceof Integer) {
                        quantity = Double.valueOf((Integer) orderData.get("quantity"));
                    } else if (orderData.get("quantity") instanceof Double) {
                        quantity = (Double) orderData.get("quantity");
                    } else {
                        quantity = Double.parseDouble(orderData.get("quantity").toString());
                    }
                    existingOrder.setQuantity(quantity > 0 ? quantity : 1.0);
                } catch (Exception e) {
                    System.out.println("解析数量出错，保留原值: " + e.getMessage());
                }
            }

            // 更新单价
            if (orderData.get("unitPrice") != null) {
                try {
                    Double unitPrice;
                    if (orderData.get("unitPrice") instanceof Integer) {
                        unitPrice = Double.valueOf((Integer) orderData.get("unitPrice"));
                    } else if (orderData.get("unitPrice") instanceof Double) {
                        unitPrice = (Double) orderData.get("unitPrice");
                    } else {
                        unitPrice = Double.parseDouble(orderData.get("unitPrice").toString());
                    }
                    existingOrder.setUnitPrice(unitPrice >= 0 ? unitPrice : 0.0);

                    // 同时更新price字段
                    existingOrder.setPrice(existingOrder.getUnitPrice());
                } catch (Exception e) {
                    System.out.println("解析单价出错，保留原值: " + e.getMessage());
                }
            }

            // 更新总金额（自动计算或使用提供的值）
            if (orderData.get("totalAmount") != null) {
                try {
                    Double totalAmount;
                    if (orderData.get("totalAmount") instanceof Integer) {
                        totalAmount = Double.valueOf((Integer) orderData.get("totalAmount"));
                    } else if (orderData.get("totalAmount") instanceof Double) {
                        totalAmount = (Double) orderData.get("totalAmount");
                    } else {
                        totalAmount = Double.parseDouble(orderData.get("totalAmount").toString());
                    }
                    existingOrder.setTotalAmount(totalAmount >= 0 ? totalAmount : 0.0);
                } catch (Exception e) {
                    System.out.println("解析总金额出错，自动计算: " + e.getMessage());
                    // 如果解析失败，自动计算总金额
                    if (existingOrder.getQuantity() != null && existingOrder.getUnitPrice() != null) {
                        existingOrder.setTotalAmount(existingOrder.getQuantity() * existingOrder.getUnitPrice());
                    }
                }
            } else {
                // 如果没有提供总金额，自动计算
                if (existingOrder.getQuantity() != null && existingOrder.getUnitPrice() != null) {
                    existingOrder.setTotalAmount(existingOrder.getQuantity() * existingOrder.getUnitPrice());
                }
            }

            // 更新单位
            if (orderData.get("unit") != null && !orderData.get("unit").toString().isEmpty()) {
                existingOrder.setUnit(orderData.get("unit").toString());
            }

            // 更新产品关联
            if (orderData.get("productId") != null) {
                try {
                    Long productId;
                    if (orderData.get("productId") instanceof Integer) {
                        productId = Long.valueOf((Integer) orderData.get("productId"));
                    } else if (orderData.get("productId") instanceof Long) {
                        productId = (Long) orderData.get("productId");
                    } else {
                        productId = Long.parseLong(orderData.get("productId").toString());
                    }

                    if (productId <= 0) {
                        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                                .body(new ApiResponse<>(false, "产品ID必须大于0", null));
                    }

                    // 从产品仓库获取产品对象并关联
                    Optional<com.trace.demo.entity.Product> product = productRepository.findById(productId);
                    if (!product.isPresent()) {
                        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                                .body(new ApiResponse<>(false, "未找到ID为 " + productId + " 的产品", null));
                    }
                    existingOrder.setProduct(product.get());

                    // 更新产品名称
                    if (product.get().getProductName() != null && !product.get().getProductName().isEmpty()) {
                        existingOrder.setProductName(product.get().getProductName());
                    } else {
                        existingOrder.setProductName("未命名产品");
                    }

                    // 更新批次号
                    if (product.get().getBatchNumber() != null && !product.get().getBatchNumber().isEmpty()) {
                        existingOrder.setBatchNumber(product.get().getBatchNumber());
                    } else {
                        existingOrder.setBatchNumber("默认批次");
                    }
                } catch (Exception e) {
                    System.out.println("解析产品ID出错: " + e.getMessage());
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "产品ID格式不正确: " + e.getMessage(), null));
                }
            }

            // 更新配送地址
            if (orderData.get("deliveryAddress") != null) {
                existingOrder.setShippingAddress(orderData.get("deliveryAddress").toString());
            }

            // 更新客户信息
            if (orderData.get("customerName") != null) {
                existingOrder.setCustomerName(orderData.get("customerName").toString());

                if (orderData.get("customerPhone") != null) {
                    existingOrder.setCustomerPhone(orderData.get("customerPhone").toString());
                }
            }

            // 更新备注
            if (orderData.get("remark") != null && !orderData.get("remark").toString().trim().isEmpty()) {
                existingOrder.setNotes(orderData.get("remark").toString());
            }

            // 更新经销商ID
            if (orderData.get("dealerId") != null) {
                try {
                    Long dealerId;
                    if (orderData.get("dealerId") instanceof Integer) {
                        dealerId = Long.valueOf((Integer) orderData.get("dealerId"));
                    } else if (orderData.get("dealerId") instanceof Long) {
                        dealerId = (Long) orderData.get("dealerId");
                    } else {
                        dealerId = Long.parseLong(orderData.get("dealerId").toString());
                    }
                    existingOrder.setDealerId(dealerId > 0 ? dealerId : 1L);
                } catch (Exception e) {
                    System.out.println("解析经销商ID出错，保留原值: " + e.getMessage());
                }
            }

            // 更新订单状态
            if (orderData.get("status") != null) {
                try {
                    String statusStr = orderData.get("status").toString();
                    Order.OrderStatus status = Order.OrderStatus.valueOf(statusStr);
                    existingOrder.setStatus(status);
                    System.out.println("订单状态已更新为: " + status);
                } catch (IllegalArgumentException e) {
                    System.out.println("无效的订单状态值: " + orderData.get("status") + ", 错误: " + e.getMessage());
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                            .body(new ApiResponse<>(false, "无效的订单状态: " + orderData.get("status"), null));
                }
            }

            // 最终验证：确保所有必填字段都有值
            if (existingOrder.getProductName() == null || existingOrder.getProductName().isEmpty()) {
                existingOrder.setProductName("未命名产品");
            }
            if (existingOrder.getBatchNumber() == null || existingOrder.getBatchNumber().isEmpty()) {
                existingOrder.setBatchNumber("默认批次");
            }
            if (existingOrder.getPrice() == null) {
                existingOrder.setPrice(existingOrder.getUnitPrice() != null ? existingOrder.getUnitPrice() : 0.0);
            }
            if (existingOrder.getUnitPrice() == null) {
                existingOrder.setUnitPrice(existingOrder.getPrice() != null ? existingOrder.getPrice() : 0.0);
            }
            if (existingOrder.getQuantity() == null) {
                existingOrder.setQuantity(1.0);
            }
            if (existingOrder.getTotalAmount() == null) {
                existingOrder.setTotalAmount(existingOrder.getQuantity() * existingOrder.getUnitPrice());
            }
            if (existingOrder.getDealerId() == null) {
                existingOrder.setDealerId(1L);
            }
            if (existingOrder.getUnit() == null || existingOrder.getUnit().isEmpty()) {
                existingOrder.setUnit("件");
            }

            // 保存更新后的订单
            System.out.println("准备保存更新后的订单数据: " + existingOrder);
            Order updatedOrder = orderRepository.save(existingOrder);
            System.out.println("订单更新成功，ID: " + updatedOrder.getId());

            return ResponseEntity.ok(new ApiResponse<>(true, "订单更新成功", updatedOrder));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "更新订单时发生错误: " + e.getMessage(), null));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteOrder(@PathVariable Long id) {
        Optional<Order> order = orderRepository.findById(id);
        if (!order.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Order not found with id: " + id, null));
        }

        orderRepository.deleteById(id);
        return ResponseEntity.ok(new ApiResponse<>(true, "Order deleted successfully", null));
    }

    @PutMapping("/{id}/ship")
    public ResponseEntity<ApiResponse<Map<String, Object>>> shipOrder(
            @PathVariable Long id,
            @RequestBody Map<String, String> logisticsData) {

        Optional<Order> optionalOrder = orderRepository.findById(id);
        if (!optionalOrder.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Order not found with id: " + id, null));
        }

        Order order = optionalOrder.get();
        order.setStatus(Order.OrderStatus.SHIPPED);
        order.setShippingDate(LocalDateTime.now());
        order.setLogisticsCompany(logisticsData.get("logisticsCompany"));
        order.setTrackingNumber(logisticsData.get("trackingNumber"));

        Order updatedOrder = orderRepository.save(order);
        // 转换为DTO并返回Map格式
        Map<String, Object> orderMap = new OrderDTO(updatedOrder).toMap();
        return ResponseEntity.ok(new ApiResponse<>(true, "Order shipped successfully", orderMap));
    }

    @PutMapping("/{id}/complete")
    public ResponseEntity<ApiResponse<Map<String, Object>>> completeOrder(@PathVariable Long id) {
        Optional<Order> optionalOrder = orderRepository.findById(id);
        if (!optionalOrder.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Order not found with id: " + id, null));
        }

        Order order = optionalOrder.get();
        order.setStatus(Order.OrderStatus.COMPLETED);
        order.setDeliveryDate(LocalDateTime.now());

        Order updatedOrder = orderRepository.save(order);
        // 转换为DTO并返回Map格式
        Map<String, Object> orderMap = new OrderDTO(updatedOrder).toMap();
        return ResponseEntity.ok(new ApiResponse<>(true, "Order completed successfully", orderMap));
    }

    @PutMapping("/{id}/cancel")
    public ResponseEntity<ApiResponse<Map<String, Object>>> cancelOrder(@PathVariable Long id) {
        Optional<Order> optionalOrder = orderRepository.findById(id);
        if (!optionalOrder.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "Order not found with id: " + id, null));
        }

        Order order = optionalOrder.get();
        order.setStatus(Order.OrderStatus.CANCELLED);

        Order updatedOrder = orderRepository.save(order);
        // 转换为DTO并返回Map格式
        Map<String, Object> orderMap = new OrderDTO(updatedOrder).toMap();
        return ResponseEntity.ok(new ApiResponse<>(true, "Order cancelled successfully", orderMap));
    }

    @GetMapping("/count")
    public ResponseEntity<ApiResponse<Long>> countOrders() {
        Long count = orderRepository.countOrders();
        return ResponseEntity.ok(new ApiResponse<>(true, "Orders count retrieved successfully", count));
    }

    @GetMapping("/count/today")
    public ResponseEntity<ApiResponse<Long>> countTodayNewOrders() {
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT);
        Long count = orderRepository.countTodayNewOrders(startOfDay);
        return ResponseEntity.ok(new ApiResponse<>(true, "Today's new orders count retrieved successfully", count));
    }

    @GetMapping("/count/status")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> countOrdersByStatus() {
        List<Map<String, Object>> distribution = orderRepository.countOrdersByStatus();
        return ResponseEntity.ok(new ApiResponse<>(true, "Orders by status count retrieved successfully", distribution));
    }

    @GetMapping("/count/last7days")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> countOrdersLast7Days() {
        LocalDateTime startDate = LocalDateTime.now().minusDays(7);
        List<Map<String, Object>> statistics = orderRepository.countOrdersLast7Days(startDate);
        return ResponseEntity.ok(new ApiResponse<>(true, "Last 7 days orders count retrieved successfully", statistics));
    }
}
